from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.ext.asyncio import async_sessionmaker
from sqlalchemy.ext.asyncio import AsyncAttrs
from sqlalchemy.orm import DeclarativeBase
from urllib.parse import quote_plus
from server.settings import Settings

db_username = Settings.database_settings.db_username
db_password = Settings.database_settings.db_password
db_host = Settings.database_settings.db_host
db_port = Settings.database_settings.db_port
db_database = Settings.database_settings.db_database
db_protocol = 'mysql+asyncmy'

if Settings.database_settings.db_type == 'postgresql':
    db_protocol = 'postgresql+asyncpg'

ASYNC_SQLALCHEMY_DATABASE_URL = (
    f'{db_protocol}://{db_username}:{quote_plus(db_password)}@'
    f'{db_host}:{db_port}/{db_database}'
)

async_engine = create_async_engine(
    ASYNC_SQLALCHEMY_DATABASE_URL,
    echo=Settings.database_settings.db_echo,
    max_overflow=Settings.database_settings.db_max_overflow,
    pool_size=Settings.database_settings.db_pool_size,
    pool_recycle=Settings.database_settings.db_pool_recycle,
    pool_timeout=Settings.database_settings.db_pool_timeout,
)
AsyncSessionLocal = async_sessionmaker(autocommit=False, autoflush=False, bind=async_engine)


class Base(AsyncAttrs, DeclarativeBase):
    pass
